import React, { useState, useEffect, useContext } from 'react';
import './index.scss';
import { Context } from "@/context/index";
// import createjs from 'preloadjs'
const preLoadPngMap = require.context('../../assets/img', true, /\.png$/);
const IMG_LOAD_TIMEOUT = 20 * 1000;

const PreloadSource = (props) => {
  const { handleClose } = props;
  let [percent, setPercent] = useState(0);
  let { content = {} } = useContext(Context) || {};
  useEffect(() => {
    // 方法一
    // var mainfest = [
    //   // { src: "@/assets/img/title-bg.png" }
    // ];
    // preLoadPngMap.keys().forEach((key) => {
    //   let _path = key.substring(2);
    //   let imgSource = require(`@/assets/img/${_path}`);
    //   mainfest.push({ src: imgSource });
    // });
    // var preload = new window.createjs.LoadQueue(true);
    // //为preloaded添加整个队列变化时展示的进度事件
    // preload.addEventListener('progress', handleFileProgress);
    // //注意加载音频文件需要调用如下代码行
    // preload.installPlugin(window.createjs.SOUND);
    // //为preloaded添加当队列完成全部加载后触发事件
    // preload.addEventListener('complete', loadComplete);
    // //设置最大并发连接数  最大值为10
    // // preload.setMaxConnections(10);
    // preload.loadManifest(mainfest);

    // 方法二
    const len = preLoadPngMap.keys().length;
    let percent = 0;
    let cnt = 0;
    let gameLoadCompeleted = false;
    let timer = null;
    preLoadPngMap.keys().forEach((key) => {
      let _path = key.substring(2);

      var img = new Image();
      let imgSource=require(`@/assets/img/${_path}`)
      img.src = imgSource;
      img.decoding = 'async';
      img.onload = () => {
        cnt++;
        percent = (cnt / len) * 100;
        handleFileProgress({ loaded: cnt / len });
        if (percent >= 100) {
          if (gameLoadCompeleted) return;
          gameLoadCompeleted = true;
          clearTimeout(timer);
          loadComplete();
        }
      };
    });
    timer = setTimeout(() => {
      if (gameLoadCompeleted) return;
      gameLoadCompeleted = true;
      handleFileProgress({ loaded: 1 });
      loadComplete();
    }, IMG_LOAD_TIMEOUT);

    function handleFileProgress(data) {
      let percent = Math.ceil(data.loaded * 100);
      setPercent(percent);
    }
    function loadComplete() {
      setTimeout(() => {
        handleClose();
      }, 500);
    }
  }, [handleClose]);

  return (
    <div className='loading-progress'>
      <div className='progress-mask'>
        <div className='content'>
          <div className='loadingio-spinner-ball'>
            <div className='ldio'>
              <div></div>
            </div>
          </div>
          <div className='ball-shadow'></div>
          <div className='progress-txt'>{percent}%</div>
        </div>
      </div>
    </div>
  );
};

export default PreloadSource;
